package com.zhx.common.common.event.Listener;


import com.zhx.common.common.event.UserRegisterEvent;
import com.zhx.common.user.dao.UserDao;
import com.zhx.common.user.domain.entity.User;
import com.zhx.common.user.domain.entity.UserBackpack;
import com.zhx.common.user.domain.enums.IdempotentEnum;
import com.zhx.common.user.domain.enums.ItemEnum;
import com.zhx.common.user.service.IUserBackpackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

@Component
public class UserRegisterListener {

    @Resource
    private IUserBackpackService userBackpackService;

    @Resource
    private UserDao userDao;

    /**
     * 当用户注册时触发该事件，向用户发放改名卡。
     *
     * @param event 用户注册事件
     * @TransactionalEventListener是Spring 我们可以通过此注解来决定该事件是和事务一起提交，还是事务提交后执行。
     * TransactionPhase.AFTER_COMMIT 事务提交后执行 默认就是这个
     */
    @Async //异步执行
    @TransactionalEventListener(classes = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    //@EventListener(classes = UserRegisterEvent.class)
    public void sendCard(UserRegisterEvent event) {
        User user = event.getUser();
        userBackpackService.acquireItem(user.getId(), ItemEnum.MODIFY_NAME_CARD.getId(), IdempotentEnum.UID, user.getId().toString());
    }


    @EventListener(classes = UserRegisterEvent.class)
    public void sendBadge(UserRegisterEvent event) {
        //前十名注册徽章
        User user = event.getUser();
        int count = userDao.count();
        if (count < 10) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP10_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        } else if (count < 100) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP100_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        }

    }
}
